import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http/http.dart' as http;
import 'package:qilo/core/constants/app_icons.dart';
import 'package:qilo/core/widgets/transgression_reporting_portal.dart';

class MysticalWisdomSanctuary extends StatefulWidget {
  const MysticalWisdomSanctuary({super.key});

  @override
  State<MysticalWisdomSanctuary> createState() =>
      _MysticalWisdomSanctuaryState();
}

class _MysticalWisdomSanctuaryState extends State<MysticalWisdomSanctuary> {
  final TextEditingController _etherealMessageController =
      TextEditingController();
  final ScrollController _cosmicScrollController = ScrollController();
  List<EnlightenedMessage> _transcendentDialogue = [];
  bool _isChannelingWisdom = false;
  String? _currentConversationEssence;
  late String _uniqueSessionIdentifier;
  bool _hasUserSentMessage = false;

  @override
  void initState() {
    super.initState();
    _generateUniqueSessionIdentifier();
    _initializeWelcomeRitual();
  }

  void _generateUniqueSessionIdentifier() {
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    final randomSuffix = _generateRandomString(16);
    _uniqueSessionIdentifier = '${timestamp}_$randomSuffix';
  }

  String _generateRandomString(int length) {
    const chars =
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = Random();
    return String.fromCharCodes(
      Iterable.generate(
        length,
        (_) => chars.codeUnitAt(random.nextInt(chars.length)),
      ),
    );
  }

  void _initializeWelcomeRitual() {
    // 不再自动发送欢迎消息，等待用户主动发送第一条消息
  }

  void _manifestBotMessage(String etherealText) {
    if (mounted) {
      setState(() {
        _transcendentDialogue.add(
          EnlightenedMessage(
            text: etherealText,
            isFromSeeker: false,
            timestamp: DateTime.now(),
          ),
        );
      });
      _scrollToCosmicBottom();
    }
  }

  void _manifestSeekerMessage(String etherealText) {
    setState(() {
      _transcendentDialogue.add(
        EnlightenedMessage(
          text: etherealText,
          isFromSeeker: true,
          timestamp: DateTime.now(),
        ),
      );
      // 标记用户已发送消息，用于切换背景
      if (!_hasUserSentMessage) {
        _hasUserSentMessage = true;
      }
    });
    _scrollToCosmicBottom();
    _channelWisdomFromAPI(etherealText);
  }

  Future<void> _channelWisdomFromAPI(String seekerQuery) async {
    setState(() {
      _isChannelingWisdom = true;
    });

    try {
      final response = await http.post(
        Uri.parse('https://api.wiseaii.com/wiseai/v1/chat'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'bundle_id': 'com.qilo.ios',
          'session_id': _uniqueSessionIdentifier,
          'content_type': 'text',
          'content': seekerQuery,
          if (_currentConversationEssence != null)
            'conversation_id': _currentConversationEssence,
        }),
      );

      if (response.statusCode == 200) {
        final responseData = jsonDecode(response.body);

        if (responseData['code'] == 1003 && responseData['data'] != null) {
          final wisdomData = responseData['data'];
          final enlightenedAnswer = wisdomData['answer'] as String?;
          final conversationEssence = wisdomData['conversation_id'] as String?;
          final manifestationDelay = wisdomData['show_sec'] as int? ?? 2;

          if (conversationEssence != null) {
            _currentConversationEssence = conversationEssence;
          }

          // Simulate the AI thinking time
          await Future.delayed(Duration(seconds: manifestationDelay));

          if (enlightenedAnswer != null && enlightenedAnswer.isNotEmpty) {
            _manifestBotMessage(enlightenedAnswer);
          }
        } else {
          _manifestBotMessage(
            "🌙 The cosmic energies seem disrupted. Please try again in a moment.",
          );
        }
      } else {
        _manifestBotMessage(
          "⚡ The mystical connection is unstable. Please try again later.",
        );
      }
    } catch (e) {
      _manifestBotMessage(
        "🔮 The wisdom channels are temporarily blocked. Please try again.",
      );
    } finally {
      setState(() {
        _isChannelingWisdom = false;
      });
    }
  }

  void _scrollToCosmicBottom() {
    Future.delayed(const Duration(milliseconds: 100), () {
      if (_cosmicScrollController.hasClients) {
        _cosmicScrollController.animateTo(
          _cosmicScrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _transmitMessage() {
    if (_etherealMessageController.text.trim().isNotEmpty) {
      _manifestSeekerMessage(_etherealMessageController.text.trim());
      _etherealMessageController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildMysticalAppBar(),
              Expanded(child: _buildEnlightenedChatRealm()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMysticalAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.w),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: Center(
              child: Text(
                'AI Guitar Assistant',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap:
                () => TransgressionReportingPortal.manifestReportingRealm(
                  context,
                  targetId: 'ai_companion_chat',
                  targetType: 'chat_content',
                  onReportSubmitted: (transgression) {
                    Navigator.of(context).pop();
                  },
                ),
            child: Icon(MyIcons.iconReport, color: Colors.white, size: 24.w),
          ),
        ],
      ),
    );
  }

  Widget _buildEnlightenedChatRealm() {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
            _hasUserSentMessage
                ? 'assets/images/activity-bg.png'
                : 'assets/images/ai-bg.png',
          ),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        children: [
          _buildCosmicStatus(),
          Expanded(child: _buildTranscendentMessagesList()),
          _buildEtherealMessageInput(),
        ],
      ),
    );
  }

  Widget _buildCosmicStatus() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
      decoration: BoxDecoration(
        color: const Color(0xFFCD8B76),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 8.w,
            height: 8.w,
            decoration: BoxDecoration(
              color: _isChannelingWisdom ? Colors.orange : Colors.green,
              shape: BoxShape.circle,
            ),
          ),
          SizedBox(width: 8.w),
          Text(
            _isChannelingWisdom
                ? 'Channeling Wisdom...'
                : 'AI Companion Online',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontFamily: 'Poppins',
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTranscendentMessagesList() {
    return ListView.builder(
      controller: _cosmicScrollController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: _transcendentDialogue.length,
      itemBuilder: (context, index) {
        return _buildEnlightenedMessageBubble(_transcendentDialogue[index]);
      },
    );
  }

  Widget _buildEnlightenedMessageBubble(EnlightenedMessage message) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            message.isFromSeeker
                ? MainAxisAlignment.end
                : MainAxisAlignment.start,
        children: [
          if (!message.isFromSeeker) ...[
            CircleAvatar(
              radius: 20.r,
              backgroundImage: const AssetImage('assets/images/avatar1.png'),
              backgroundColor: Colors.grey[300],
              child: const Icon(
                Icons.auto_awesome,
                color: Colors.white,
                size: 16,
              ),
            ),
            SizedBox(width: 12.w),
          ],
          Flexible(
            child: Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color:
                    message.isFromSeeker
                        ? const Color(0xFFCD8B76)
                        : const Color(0xFFD4A574),
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Text(
                message.text,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                  height: 1.4,
                ),
              ),
            ),
          ),
          if (message.isFromSeeker) ...[
            SizedBox(width: 12.w),
            CircleAvatar(
              radius: 20.r,
              backgroundImage: const AssetImage('assets/images/avatar2.png'),
              backgroundColor: Colors.grey[300],
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildEtherealMessageInput() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24.r,
            backgroundImage: const AssetImage('assets/images/avatar2.png'),
            backgroundColor: Colors.grey[300],
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Container(
              height: 60.h,
              decoration: BoxDecoration(
                color: const Color(0xFFD4A574).withValues(alpha: 0.8),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: TextField(
                        controller: _etherealMessageController,
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                          fontFamily: 'Poppins',
                        ),
                        decoration: InputDecoration(
                          hintText: 'Ask the mystical AI...',
                          hintStyle: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white.withValues(alpha: 0.7),
                            fontFamily: 'Poppins',
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.zero,
                        ),
                        onSubmitted: (_) => _transmitMessage(),
                        enabled: !_isChannelingWisdom,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(6.w),
                    child: GestureDetector(
                      onTap: _isChannelingWisdom ? null : _transmitMessage,
                      child: Container(
                        width: 48.w,
                        height: 48.w,
                        decoration: BoxDecoration(
                          color:
                              _isChannelingWisdom
                                  ? Colors.grey
                                  : const Color(0xFFCD8B76),
                          shape: BoxShape.circle,
                        ),
                        child:
                            _isChannelingWisdom
                                ? SizedBox(
                                  width: 18.w,
                                  height: 18.w,
                                  child: const CircularProgressIndicator(
                                    color: Colors.white,
                                    strokeWidth: 2,
                                  ),
                                )
                                : Icon(
                                  MyIcons.iconSend,
                                  color: Colors.white,
                                  size: 18.w,
                                ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _etherealMessageController.dispose();
    _cosmicScrollController.dispose();
    super.dispose();
  }
}

class EnlightenedMessage {
  final String text;
  final bool isFromSeeker;
  final DateTime timestamp;

  EnlightenedMessage({
    required this.text,
    required this.isFromSeeker,
    required this.timestamp,
  });
}
